﻿
// TODO: Move to project

using System;
namespace Gwn.Utilities.Extensions
{
    public static class ObjectExtension
    {
        private static string GetTypeName<T>()
        {
            return typeof(T).Name.ToLower();
        }

        public static T GetTypeOf<T>(this object objToConvert)
        {
            object result = null;
            var dbNull = "<null>";

            switch (GetTypeName<T>())
            {
                case "boolean":
                    result = Boolean.Parse(objToConvert.ToString());
                    break;

                case "string":
                    if (objToConvert.ToString() == dbNull)
                        result = "";
                    else
                        result = objToConvert.ToString();
                    break;

                case "int32":
                    if (objToConvert.ToString() == dbNull)
                        result = 0;
                    else
                        result = Int32.Parse(objToConvert.ToString());
                    break;

                case "char":
                    if (objToConvert.ToString() == dbNull)
                        result = ' ';
                    else
                    {
                        char chrValue;
                        Char.TryParse(objToConvert.ToString(), out chrValue);
                        result = chrValue;
                    }
                    break;

                case "double":
                    if (objToConvert.ToString() == dbNull)
                        result = 0;
                    else
                        result = double.Parse(objToConvert.ToString());
                    break;

                case "datetime":
                    DateTime dtValue;
                    DateTime.TryParse(objToConvert.ToString(), out dtValue);
                    result = dtValue;
                    break;

                case "decimal":
                    if (objToConvert.ToString() == dbNull)
                        result = 0;
                    else
                    {
                        Decimal decValue;
                        Decimal.TryParse(objToConvert.ToString(), out decValue);
                        result = decValue;
                    }
                    break;

                case "guid":
                    if (objToConvert.ToString() == dbNull)
                        result = "";
                    else
                        result = new Guid(objToConvert.ToString());

                    break;
            }

            if (result != null)
                return (T)result;

            return default(T);
        }
    }
}
